package zk_01.zookeeper;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

public class Client implements Watcher{
	private ZooKeeper zk;
	private String hostPort;
	
	
	public Client(){}
	
	public Client(String hostPort){
		this.hostPort=hostPort;
	}
	
	public void startZK() throws IOException{
		zk = new ZooKeeper(hostPort,15000,this);
	}
	
	public void stopZK() throws InterruptedException{
		zk.close();
	}
	
	public String queueCommand(String cmd) throws InterruptedException{
		while(true){
			try {
				String name = zk.create("/tasks/task-", cmd.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
				return name;
			} catch (KeeperException e) {
				e.printStackTrace();
				if (e instanceof NodeExistsException){//如果异常是NodeExistsException,退出循环
					System.out.println("task already exists");
					return null;
				}else if(e instanceof ConnectionLossException){
					//如果异常是ConnectionLossExcetipn,检测任务节点是否已经创建成功，成功退出循环，否则继续循环尝试创建
					//因为是用的ZK自增的节点，没法知道异常时的NAME，所以不做处理
					//-----------------------稍后来处理--------------------------
					return null;
				}else{
					return null;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		Client client = new Client("10.40.20.181:2181");
		
		try {
			client.startZK();
			String name = client.queueCommand("this is my first task");
			
			System.out.println("task name is:"+name);
			client.stopZK();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void process(WatchedEvent event) {
		System.out.println(event);
	}
}
